#include <iostream>
#include <unistd.h>
#include  <string>
#include <pthread.h>
#include <cstdlib>

using namespace std;

class Request
{

public:
    //初始化变量
    Request(int start,int end, const string &threadname)
    : start_(start), end_(end), threadname_(threadname)
    {}

public:
    int start_;
    int end_;
    string threadname_;
};

class Response
{
public:
    //初始化变量
    Response(int result,int exitcode)
    : result_(result),exitcode_(exitcode)
    {}

public:
    int result_;//计算结果
    int exitcode_;//计算结果是否可靠
};


void *sumCount(void *args)
{
    Request *rq = static_cast<Request*>(args);
    Response *rsp =  new Response(0,0);
    for(int i = rq->start_; i <= rq->end_; i++)
    {
        cout << rq->threadname_ << " is runing, caling..., " << i << endl;
        rsp->result_ += i;
        usleep(100000);
    }
    delete rq;
    return rsp;

}
int main()
{
    pthread_t  tid;
    //创建一个rq对象
    Request *rq = new Request(1, 100, "thread 1");
    //创建一个新线程 
    pthread_create(&tid,nullptr,sumCount,rq);

    void *ret;
    //等待线程结束
    pthread_join(tid,&ret);
    //强转
    Response *rsp = static_cast<Response *>(ret);
    cout <<"rsp->result: " << rsp->result_ << ", rsp->exitcode_: " << rsp->exitcode_ << endl;
    delete rsp;
    return 0;

}

// int g_val = 100;

// //new thread
// void* threadRoutine(void* args)
// {
//     const char *name = (const char*)args;
//     int cnt = 5;
//     while(true)
//     {
//         // cout << "new thraed pid : " << getpid() << endl;
//         // sleep(2);
//         printf("%s,  pid: %d, g_val: %d, &g_val: 0x%p\n",name, getpid(),g_val, &g_val);
//         sleep(1);
//         cnt--;
//         if(cnt == 0)break;
//     }
//     // return (void*)1;
// }

// int main()
// {
//     pthread_t tid;
//     //创建一个线程 
//     pthread_create(&tid, nullptr, threadRoutine,(void*)"Thread 1");

//     sleep(3);
//     pthread_cancel(tid);//参数是线程的id

//     // while(true)
//     // {
//     //     cout << "main thraed pid : " << getpid() << endl;
//     //     sleep(1);
//     // }

//     void *retval;
//     pthread_join(tid,&retval);

//     cout << "main thread quit ...,ret: " << (long long int)retval <<endl;
//     return 0;
// }
